import {createRouter, createWebHashHistory} from 'vue-router'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import {ElMessage} from "element-plus";

const router = createRouter({
    //
    history: createWebHashHistory(), // hash模式
    routes: [
        {
            path: '/login',
            name: 'login',
            component: Login
        },
        {
            path: '/',
            component: Dashboard,
            children: [
                {
                    path: '',
                    redirect: '/home'
                },
                {
                    path: 'home',
                    name: 'home',
                    component: () => import('../views/dashboard/Home.vue')
                },
                {
                    path: 'child',
                    name: 'child',
                    component: () => import('../views/child/ChildList.vue')
                },
                {
                    path: 'elder',
                    name: 'elder',
                    component: () => import('../views/elder/ElderList.vue')
                },
                {
                    path: 'doctor',
                    name: 'doctor',
                    component: () => import('../views/doctor/DoctorList.vue')
                },
                {
                    path: 'community',
                    name: 'community',
                    component: () => import('../views/community/CommunityList.vue')
                }
            ]
        }
    ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
    console.log('路由守卫触发:', {to: to.path, from: from.path})
    const token = localStorage.getItem('token')
    console.log('当前token:', token)

    // 如果访问登录页
    if (to.path === '/login') {
        console.log('访问登录页')
        // 如果已经有token，重定向到首页
        if (token) {
            console.log('已有token，重定向到首页')
            ElMessage.info('已有token，重定向到首页');
            next('/home')
        } else {
            console.log('无token，允许访问登录页')
            next()
        }
        return
    }

    // 如果访问其他页面
    if (!token) {
        console.log('无token，重定向到登录页')
        ElMessage.error('无token，重定向到登录页');
        next('/login')
        return
    }

    console.log('有token，允许访问')
    next()
})

export default router 